package czhdao

import (
	"Cgo/front/models"
	"Cgo/global"
	"errors"
)

type strategyDao struct{}

var StrategyDao = strategyDao{}

// 获取所有文章;
func (s strategyDao) GetAllStrategy() ([]models.CzhStrategy, error) {
	var allStrategy []models.CzhStrategy
	if r := global.DB.Raw("SELECT * FROM czh_strategy").Scan(&allStrategy); r.RowsAffected > 0 {
		return allStrategy, nil
	} else {
		return allStrategy, errors.New("没有查到数据")
	}
}

// 根据文章id获取对应信息
func (s strategyDao) GetStrategyById(id string) (models.CzhStrategy, error) {
	var strategy models.CzhStrategy
	if r := global.DB.Raw("SELECT * FROM czh_strategy WHERE id = ?", id).Scan(&strategy); r.RowsAffected > 0 {
		return strategy, nil
	} else {
		return strategy, errors.New("没有查到数据")
	}
}

// 编辑文章
func (s strategyDao) EditStrategy(title string, detail string, username string, userid string, coverimg string, imglist string) error {
	if r := global.DB.Exec("INSERT INTO czh_strategy (title, detail, username, userid, coverimg, imglist) VALUES (?, ?, ?, ?, ?, ?)", title, detail, username, userid, coverimg, imglist); r.Error != nil {
		return r.Error
	} else {
		return nil
	}
}

// 根据关键字查询相关文章
func (s strategyDao) GetStrategyByTitle(title string) ([]models.CzhStrategy, error) {
	var strategyList []models.CzhStrategy
	if r := global.DB.Raw("SELECT * FROM czh_strategy WHERE title LIKE CONCAT('%', ?, '%')", title).Scan(&strategyList); r.RowsAffected > 0 {
		return strategyList, nil
	} else {
		return strategyList, errors.New("没有查到数据")
	}
}
